package cac.fenjian.resource.outBill.rest;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.fenjian.resource.MsWorkbinMaterial.dto.MsWorkbinMaterialDTO;
import cac.fenjian.resource.WmsInvOutBillH.dto.WmsInvOutBillHDTO;
import cac.fenjian.resource.itemOutBill.dao.ItemInventoryOutbillDao;
import cac.fenjian.resource.itemOutBill.service.ItemOutBillService;
import cac.fenjian.resource.outBill.dao.ReturnApplyDao;
import cac.fenjian.resource.outBill.service.WmsInvOutBillService;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program test-curd
 * @description 出库申请主（子）表接口
 * @author: xiaojian
 * @create: 2022-08-29-16-00
 **/
@RestController
@RequestMapping("/outBill")
@Slf4j
public class WmsInvOutBillRest {
    @Autowired
    private WmsInvOutBillService wmsInvOutBillService;
    @Autowired
    private ItemOutBillService itemOutBillService;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private ReturnApplyDao returnApplyDao;
    @Autowired
    private ItemInventoryOutbillDao itemInventoryOutbillDao;

    /**
     * 根据map 内容插入出库申请单接口
     * @param map
     * @return
     */

    @PostMapping("/insertWmsInvOutBill")
    @Transactional
    public ResponseMsg<Map> insertWmsInvOutBillH(@RequestBody HashMap<String,Object> map){
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId= (String) request.getSession().getAttribute("account");
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        List<HashMap<String,Object>> maps = (List<HashMap<String, Object>>) map.get("data");
        if(maps.size() == 0){
            return responseMsg.setRetCode("201").setMessage("物料出库失败！");
        }
        for(int i=0;i<maps.size();i++){
            Map<String,Object> map1=new HashMap<String,Object>();
            map1 = maps.get(i);
            //状态为保管待接收、图号不为空
            if("4".equals(map1.get("returnStatus")) && !"0".equals(map1.get("returnQty")) && map1.get("itemCode")!=null && !"".equals(map1.get("itemCode"))){
                try {

                    //对出库单主表子表及库房事务表进行数据插入
                    wmsInvOutBillService.insertWmsInvOutBillHMany(map1);
                    //更新台账表信息
                    itemOutBillService.updateWmsItemInventory(map1);
                    String wmsReturnApplyId = (String) map1.get("wmsReturnApplyId");
                    //判断已经退库的数量，若为零，则将退库状态改为结束
                    Integer notReturnQty= itemOutBillService.notReturnQtySearch(wmsReturnApplyId);
                    if(notReturnQty <= 0){
                        itemOutBillService.returnStatusUp(wmsReturnApplyId);
                        //修改交接单状态
                        itemInventoryOutbillDao.updateDeliveryPlan(map1);

                    }
                    //判断该图号的类型
                    HashMap itemType = returnApplyDao.itemTypeQuery(map1);
                    String parameters = null;
                    if(itemType==null){
                        responseMsg.setRetCode("201");
                        responseMsg.setMessage("请查询物料图号"+map1.get("itemCode")+"是否在MDS_ITEM表中存在");
                        return responseMsg;
                    }
                    else {
                        if(itemType.get("itemType").equals("Z")){
                            parameters=wmsInvOutBillService.applyCancelStockBzj(map1,IP);
                        }
                        else {
                            parameters=wmsInvOutBillService.applyCancelStock(map1,IP);
                        }
                    }

                    String code="sendBData";
                    String name="两网传输-发送业务数据";
                    String sendScenario = "101发起退库";
                    long beginTime = System.currentTimeMillis();
                    log.info("======开始时间======="+beginTime);
                    callInterfaceService.sendBData(code,name,parameters,sendScenario);
                    long endTime = System.currentTimeMillis();
                    log.info("======消耗时间======="+(endTime-beginTime)+"ms");
                    s++;
                }catch(Exception e)
                {
                    e.printStackTrace();
                    f++;
                }
            }
            else f++;
        }
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("物料出库失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("物料出库成功！");
        }
        if (s != 0 && f != 0) {
            responseMsg.setRetCode("202");
            responseMsg.setMessage("物料出库有失败项！");
            responseMsg.setResponseBody(reMsg);
        }
        return responseMsg;
    }
    //缓存箱扫码
    @PostMapping("/outBillQuery")
    public ResponseMsg<List<MsWorkbinMaterialDTO>> outBillQuery(@RequestBody HashMap map){
        ResponseMsg<List<MsWorkbinMaterialDTO>> responseMsg = new ResponseMsg<>();
        List<MsWorkbinMaterialDTO> msWorkbinMaterialDTO = itemOutBillService.outBillQuery(map);
        if(msWorkbinMaterialDTO.size()!=0) {
            responseMsg.setResponseBody(msWorkbinMaterialDTO).setRetCode("200");
        }else {
            responseMsg.setResponseBody(msWorkbinMaterialDTO).setRetCode("201").setMessage("缓存箱条码有误！");
        }
        return responseMsg;
    }

}
